<template>
  <div class="login">
    <el-dialog title="登录" :visible.sync="loginVisible" width="300px" center>
      <el-form :model="login_form" :rules="loginFormRules" ref="login_form">
        <el-form-item prop="userName">
          <el-input
            placeholder="请输入账号"
            prefix-icon="el-icon-user-solid"
            v-model="login_form.userName"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-view"
            v-model="login_form.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="on_login" type="primary" size="medium" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import usersAPI from "../request/api/usersAPI";
export default {
  name: "VueStoreLogin",

  data() {
    let validate = (rule, value, callback) => {
      if (/^[a-zA-Z][a-zA-Z0-9_]{4,15}$/.test(value)) {
        callback();
      } else {
        callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    return {
      login_form: {
        userName: "",
        password: "",
      },
      loginFormRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: validate, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validate, trigger: "blur" },
        ],
      },
    };
  },

  mounted() {},

  methods: {
    on_login() {
      this.$refs.login_form.validate(async (valid) => {
        if (valid) {
          // 通过校验请求数据
          let { data: res } = await usersAPI.login(this.login_form);
          console.log(res);
          if (res.code == "001") {
            this.loginVisible = false;
            // 用户信息存储到vuex中
            this.$store.commit("setUser", res.user);
            //把返回的信息存储到本次缓存
            window.localStorage.setItem("user", JSON.stringify(res.user));
            this.$notify({
              title: "成功",
              message: res.msg,
              type: "success",
            });
          } else {
            this.$notify.error({
              title: "错误",
              message: res.msg,
            });
          }
        }
      });
    },
  },
  computed: {
    loginVisible: {
      get() {
        //读的时候会触发这个get方法
        console.log(
          "this.$store.getters.getShowLogin",
          this.$store.getters.getShowLogin
        );
        //获取vuex中的getShowLogin
        return this.$store.getters.getShowLogin;
      },
      set(value) {
        //写的时候会触发这个方法
        //把最新的值在更新到vuex中保持数据的一致性
        this.$store.commit("setShowLogin", value);
      },
    },
  },
};
</script>

<style lang="scss" scoped>
</style>